package com.itstyle.blog.service.impl;

import com.itstyle.blog.common.dynamicquery.DynamicQuery;
import com.itstyle.blog.common.limit.ServiceLimit;
import com.itstyle.blog.common.redis.RedisUtil;
import com.itstyle.blog.common.util.IPUtils;
import com.itstyle.blog.entity.Blog;
import com.itstyle.blog.service.IBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BlogServiceImpl implements IBlogService {

    @Autowired
    private DynamicQuery dynamicQuery;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ServiceLimit(limitType= ServiceLimit.LimitType.IP)
    public Blog getById(Long id) {
        String key = IPUtils.getIpAddr()+"_blog_"+id;
        boolean flag =  redisUtil.hasKey(key);
        if(!flag){
            redisUtil.set(key,key,10);
            String nativeSql = "UPDATE blog SET views = views+1 WHERE id=?";
            dynamicQuery.nativeExecuteUpdate(nativeSql,new Object[]{id});
        }
        return getBlog(id);
    }

    @Cacheable(cacheNames ="blog")
    public Blog getBlog(Long id) {
        String nativeSql = "SELECT * FROM blog WHERE id=?";
        return dynamicQuery.nativeQuerySingleResult(Blog.class,nativeSql,new Object[]{id});
    }
}